﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.XPath;

namespace WebAppMatrix.Extensions
{
    public static class IOExtensions
    {
        private static string appAbsoluteFolder;
        /// <summary>
        /// 获取当前应用程序的根目录，字符串最后会带有斜杠'\'。例如 C:\program files\app\
        /// 需要将相对路径转换为绝对路径时，请调用GenerateAbsolutePath方法
        /// </summary>
        public static string AppAbsoluteFolder
        {
            get
            {
                if (appAbsoluteFolder.IsNullOrEmpty())
                    appAbsoluteFolder = AppDomain.CurrentDomain.BaseDirectory;
                return appAbsoluteFolder;
            }
        }

        /// <summary>
        /// 如果为相对路径，则会基于当前应用程序的目录生成绝对路径
        /// 如果为绝对路径，则不会处理，直接返回
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GenerateAbsolutePath(string path)
        {
            path = path.Replace("/", "\\").TrimStart('\\');

            if (Path.IsPathRooted(path))
                return path;

            return Path.Combine(AppAbsoluteFolder, path);
        }

        /// <summary>
        /// 获取Xml文档中节点的值
        /// </summary>
        /// <param name="xpath"></param>
        /// <param name="xmlFilePath"></param>
        /// <returns></returns>
        public static string GetXmlNodeValue(string xpath, string xmlFilePath)
        {
            XPathDocument xpathDoc = new XPathDocument(xmlFilePath);
            XPathNavigator nav = xpathDoc.CreateNavigator();
            XPathExpression expression = nav.Compile(xpath);

            XPathNavigator xpathNavigator = nav.SelectSingleNode(expression);
            if (xpathNavigator != null)
            {
                return xpathNavigator.Value;
            }

            return null;
        }
    }
}
